package com.mxx.common.utils.qr;

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Auther: Mr. Zeng
 * @Date: 2020/5/20 10:00
 * @Description: 暂无描述
 */
@Slf4j
public class QrCodeUtil {
    private static final long serialVersionUID = 1L;
    private static final int QR_COLOR = -16777216;
    private static final int BG_WHITE = -1;
    private static Map<EncodeHintType, Object> hints = new HashMap<>();

    public QrCodeUtil() {
    }

    public static void generateQRCode(String text, int width, int height, String format, File codeFile) {
        BufferedImage image = generateBufferedImage(text, width, height);
        imageWriter(image, format, codeFile);
    }

    public static void generateQRCode(String text, int width, int height, String format, OutputStream outputStream) {
        BufferedImage image = generateBufferedImage(text, width, height);
        imageWriter(image, format, outputStream);
    }

    public static void generateLogoQRCode(String text, int width, int height, String format, File logoFile, File codeFile) {
        BufferedImage image = generateLogoBufferedImage(text, width, height, logoFile);
        imageWriter(image, format, codeFile);

    }

    public static void generateLogoQRCode(String text, int width, int height, String format, File logoFile, OutputStream outputStream) {
        BufferedImage image = generateLogoBufferedImage(text, width, height, logoFile);
        imageWriter(image, format, outputStream);

    }

    public static String parseQrCode(InputStream inputStream) throws IOException, NotFoundException {
        BufferedImage image = ImageIO.read(inputStream);
        return parseQRCode(image);
    }

    public static String parseQrCode(File qrCodeFile) throws IOException, NotFoundException {
        BufferedImage image = ImageIO.read(qrCodeFile);
        return parseQRCode(image);
    }

    public static String parseQRCode(BufferedImage image) throws NotFoundException {
        String content = "";
        LuminanceSource source = new BufferedImageLuminanceSource(image);
        Binarizer binarizer = new HybridBinarizer(source);
        BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
        Map<DecodeHintType, Object> hints = new HashMap();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        MultiFormatReader formatReader = new MultiFormatReader();
        Result result = formatReader.decode(binaryBitmap, hints);
        log.info("result 为：" + result.toString());
        log.info("resultFormat 为：" + result.getBarcodeFormat());
        log.info("resultText 为：" + result.getText());
        content = result.getText();
        return content;
    }


    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, 1);

        for (int x = 0; x < width; ++x) {
            for (int y = 0; y < height; ++y) {
                image.setRGB(x, y, matrix.get(x, y) ? -16777216 : -1);
            }
        }
        return image;
    }

    private static void imageWriter(BufferedImage image, String format, File codeFile) {
        try {
            ImageIO.write(image, format, codeFile);
        } catch (IOException ex) {
            throw new RuntimeException("输出二维码失败", ex);
        }
    }

    private static void imageWriter(BufferedImage image, String format, OutputStream outputStream) {
        try {
            ImageIO.write(image, format, outputStream);
        } catch (IOException ex) {
            throw new RuntimeException("输出二维码失败", ex);
        }
    }

    private static BufferedImage generateBufferedImage(String text, int width, int height) {
        try {
            BitMatrix bitMatrix = (new MultiFormatWriter()).encode(text, BarcodeFormat.QR_CODE, width, height, hints);
            BufferedImage image = toBufferedImage(bitMatrix);
            image.flush();
            return image;
        } catch (Exception ex) {
            throw new RuntimeException("生成二维码失败", ex);
        }
    }

    private static BufferedImage generateLogoBufferedImage(String text, int width, int height, File logoFile) {
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            BitMatrix bitMatrix = multiFormatWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
            BufferedImage image = toBufferedImage(bitMatrix);
            int imageWidth = image.getWidth();
            int imageHeight = image.getHeight();
            if (Objects.nonNull(logoFile) && logoFile.exists()) {
                Graphics2D g = image.createGraphics();
                BufferedImage logo = ImageIO.read(logoFile);
                g.drawImage(logo, imageWidth * 2 / 5, imageHeight * 2 / 5, imageWidth * 2 / 10, imageHeight * 2 / 10, (ImageObserver) null);
                g.dispose();
                logo.flush();
            }
            image.flush();
            return image;
        } catch (Exception ex) {
            throw new RuntimeException("生成带Logo二维码失败", ex);
        }
    }


}
